import { Component, OnInit, ViewContainerRef, ElementRef, ViewChild, AfterViewInit, OnDestroy, AfterContentChecked } from '@angular/core';
import { ElectronService } from '../../providers/electron.service';
import { DiskInfo } from '../../models/diskinfo';
import { BaseComponent } from '../base.component';
import { DisklistComponent } from '../disklist/disklist.component';
import { FilelistComponent } from '../filelist/filelist.component';
import { BeforeOpenFileEventArgs } from '../../models/eventargs';
import { FileInfo } from '../../models/fileinfo';
import { JSZipWrapper } from '../../utils/ziputils';
import { FSUtils } from '../../utils/fsutils';
import { ZipviewComponent } from '../zipview/zipview.component';

@Component({
  selector: 'app-mycomputer',
  templateUrl: './mycomputer.component.html',
  styleUrls: ['./mycomputer.component.scss']
})
export class MyComputerComponent extends BaseComponent implements OnInit, OnDestroy, AfterViewInit {
  /**标识是否正在加载数据 */
  isLoading = true;
  /**标识是否处于首页 */
  isHome = true;
  /**标识是否能返回上层 */
  canGotoLastLevel: boolean;
  /**异常信息 */
  exception: any;
  /**当前磁盘信息 */
  currentDisk: DiskInfo;
  /**当前目录信息 */
  currentDirecory: string;
  isViewVisible: boolean;
  currentFile: FileInfo;
  @ViewChild('operation') private operationElement: ElementRef;
  @ViewChild('list') private listElement: ElementRef;
  @ViewChild('bottom') private bottomElement: ElementRef;
  @ViewChild(DisklistComponent) diskListComponent: DisklistComponent;
  @ViewChild(FilelistComponent) filelistComponent: FilelistComponent;
  @ViewChild(ZipviewComponent) zipviewComponent: ZipviewComponent;
  private resizeListener: any;
  //#endregion

  /**
   * 构造函数
   * @param electronService electron服务实例
   * @param el dom元素
   */
  constructor(electronService: ElectronService,
    el: ElementRef) {
      super(electronService, el);
      this.electronService.onSelectedFiles.subscribe(files => {
        alert(`selected ${files.length} files`);
      });
      this.electronService.onSelectedDirectorys.subscribe(files => {
        alert(`selected ${files.length} directories`);
      });
  }

  ngOnInit() {
  }
  ngOnDestroy() {
  }
  ngAfterViewInit() {
    this.executeAfterTimes(() => this.diskListComponent.tryEnumDisks());
  }
  /**
   * 返回上层
   */
  gotoLastLevel(): void {
    if (!this.isHome) {
      if (this.filelistComponent) {
        if (this.currentFile) {
          const isZip = this.currentFile.isZip;
          if (isZip) {
            if (this.zipviewComponent) {
              if (!this.zipviewComponent.isInRoot) {
                this.zipviewComponent.gotoLastLevel();
                return;
              }
            }
          }
          this.currentFile = null;
          this.isViewVisible = false;
          if (isZip) {
            this.currentDirecory = this.filelistComponent.curDirecory;
            return;
          }
        }
        this.filelistComponent.gotoLastLevel();
      }
    }
  }
  /**
   * 打开磁盘
   * @param disk 待打开的磁盘
   */
  openDisk(disk: DiskInfo) {
    if (disk) {
      this.currentDisk = disk;
      this.currentDirecory = disk.path;
      this.isHome = false;
    }
  }
  /**
   * 返回首页
   */
  GoHome() {
    this.isHome = true;
    if (this.diskListComponent) {
      this.executeAfterTimes(() => {
        this.diskListComponent.tryEnumDisks();
      }, 10);
    }
  }
  /**
   * 加载zip内容前进行的处理
   */
  beforeLoadZipEntries() {
    this.isLoading = true;
  }
  /**
   * 加载zip内容完成进行的处理
   */
  loadZipEntriesCompleted() {
    this.isLoading = false;
    if (this.zipviewComponent) {
      let curZipDir = this.zipviewComponent.curDirectory;
      curZipDir = curZipDir.startsWith('/') ? curZipDir : `/${curZipDir}`;
      this.currentDirecory = `${this.currentFile.fileName} ${curZipDir}`;
    }
  }
  /**
   * 枚举磁盘之前处理
   */
  beforeEnumDisks() {
    this.isLoading = true;
  }
  /**
   * 枚举逻辑磁盘完成处理
   */
  enumDisksCompleted() {
    this.currentDirecory = '';
    this.canGotoLastLevel = false;
    this.isLoading = false;
  }
  /**
   * 枚举文件之前处理
   */
  beforeEnumFiles() {
    this.isLoading = true;
  }
  /**
   * 枚举文件信息完成处理
   */
  enumFilesCompleted() {
    if (this.filelistComponent) {
      this.canGotoLastLevel = this.filelistComponent.CheckCanGotoLastLevel();
      this.currentDirecory = this.filelistComponent.curDirecory;
    }
    this.isLoading = false;
  }
  /**
   * 打开文件之前进行的处理
   * @param args 参数
   */
  beforeOpenFile(args: BeforeOpenFileEventArgs) {
    if (args.file) {
      const file = args.file;
      if (file.isImage || file.isMp4 || file.isZip || file.isTextFormat) {
        this.currentFile = args.file;
        this.isViewVisible = true;
        args.canceled = true;
      }
    }
  }
  /**
   * 关闭查看器处理
   */
  onCloseViewer() {
    this.currentFile = null;
    this.isViewVisible = false;
  }
  test() {
    //#region JSZip test
    // const JSZip = require('jszip');
    // const zip = new JSZip();
    // zip.file('测试文件.txt', '测试文本');
    // zip.generateAsync({type: 'base64'}).then(function (base64) {
    //   location.href = 'data:application/zip;base64,' + base64;
    // });
    // console.log(zip);
    // return;
    //#endregion

    //#region file search
    const source = 'C:\\windows\\system32';
    const regExp = /(?:jpg|exe|ini)$/;
    const syncFiles = FSUtils.findFiles(source, regExp , true);
    console.log(`findFiles find ${syncFiles ? syncFiles.length : 0} files`);
    FSUtils.findFilesAsync(source, regExp, true)
    .then(files => {
      console.log(`findFilesAsync find ${files ? files.length : 0} files`);
      files.forEach((value, index) => {
        console.log(value);
        if (index > 1000) {
          throw new Error('');
        }
      });
    })
    .catch(error => {
      console.log(`findFilesAsync happend:${error}`);
    });
    //#endregion

    return;

    //#region zip test
    const dir = 'C:\\Users\\Administrator\\Documents\\';
    const zip1 = new JSZipWrapper();
    zip1.addLocalFile(`${dir}test1.h264`);
    zip1.addLocalFile(`${dir}test2.h264`, 'dir1/dir2/dir3');
    zip1.addLocalFile(`${dir}1月28号前考勤.xlsx`);
    zip1.addLocalFolder(`${dir}Navicat`, 'child-dir1');
    zip1.addLocalFolder(`${dir}智慧课堂`, 'child-dir2');
    zip1.addText('测试文本', '测试文件.txt');
    zip1.saveTo('e:\\temp\\out\\2.zip', (error, status) => {
      console.log('create zip ' + (status ? 'success' : 'failure') + '!');
    }, metaData => {
      // console.log(metaData);
      // console.log(`progress:${metaData.percent.toFixed(2)}%,current file:${metaData.currentFile}`);
    });
    zip1.saveToBase64String((error, base64) => {
      if (!error) {
        console.log(base64);
      }
    });
    console.log(zip1);

    const zip2 = new JSZipWrapper('e:\\temp\\out\\2.zip', (_err, z) => {
      if (_err) {
        console.log('加载zip文件出错' + _err);
      }
      console.log(z.getEntries());
      console.log(zip2.getEntry('package.json'));
      z.readAsTextAsync('test1.h264', (error, text) => {
        console.log(text.substring(0, 200));
      });
      z.readAsFileAsync('test1.h264', (error, data) => {
        if (!error) {
          console.log(`read file data length:${data.length}`);
        } else {
          console.log(`read file data error:${error}`);
        }
      });
      z.extractEntryTo('test1.h264', 'e:\\temp\\out\\', (error, status) => {
        console.log(`extract file ${status ? 'success' : 'failure(' + error + ')'}`);
      }, true, true);
      z.extractAllToAsync('e:\\temp\\out\\', (error, status) => {
        console.log(`extract all files ${status ? 'success' : 'failure(' + error + ')'}`);
      }, true);
      z.removeEntry('dir1');
      z.removeEntry('测试文件.txt');
      z.saveTo('e:\\temp\\out\\3.zip', (error, status) => {
        console.log('save zip to e:\\temp\\out\\3.zip' + (status ? 'success' : 'failure') + '!');
      });
    });
    console.log(zip2);
    // const zip = new Zip();
    // const dir = 'C:\\Users\\Administrator\\Documents\\';
    // console.log(zip);
    // zip.addLocalFile(`${dir}test1.h264`);
    // zip.addLocalFile(`${dir}test2.h264`, 'dir1/dir2/dir3');
    // zip.addLocalFile(`${dir}1月28号前考勤.xlsx`);
    // const date = new Date();
    // const fileName = `${date.getHours()}${date.getMilliseconds()}${date.getSeconds()}${date.getMilliseconds()}`;
    // console.log(zip.getEntry('test1.h264'));
    // zip.saveAs('E:\\temp\\' + fileName + '.zip', error => console.log(error || 'no error'));
    // zip.extractAllTo('e:\\temp\\out2\\', true);

    // const zip2 = new Zip('e:\\temp\\out\\1.zip');
    // zip2.getEntries().forEach(item => {
    //   console.log(item.entryName);
    // });
    // zip2.extractAllTo('e:\\temp\\out\\', true);

    // const zipEntries = zip.getEntries();
    // if (zipEntries && zipEntries.length > 0) {
    //   console.log(zipEntries);
    //   const entry = zipEntries[0];
    //   if (entry.isDirectory) {
    //     console.log(entry);
    //   }
    //   // console.log(entry.packHeader());
    //   // entry.getCompressedDataAsync(data => {
    //   //   console.log(data);
    //   // });
    //   // entry.getDataAsync(data => {
    //   //   console.log(data);
    //   // }, null);
    // }
    //#endregion
  }
}
